const { MarketDepartment, Student } = require('../models/db');

const ok = (res, data, extra = {}) => res.json({ success: true, data, ...extra });
const fail = (res, code = 500, message = '服务器错误') => res.status(code).json({ success: false, message, code });

const mapMarketDepartmentToClient = (m) => ({
  id: m._id?.toString(),
  name: m.name,
  manager: m.manager,
  studentCount: m.studentCount,
  graduateStatus: m.graduateStatus || [],
  createdAt: m.createdAt ? new Date(m.createdAt).toISOString() : undefined,
  updatedAt: m.updatedAt ? new Date(m.updatedAt).toISOString() : undefined,
});

const mapClientToMarketDepartment = (body) => ({
  name: body.name,
  manager: body.manager,
  studentCount: body.studentCount || 0,
  graduateStatus: body.graduateStatus || [],
  updatedAt: new Date(),
});

exports.getAllMarketDepartments = async (req, res) => {
  try {
    const { page = 1, limit = 20 } = req.query;
    const skip = (parseInt(page) - 1) * parseInt(limit);
    
    const departments = await MarketDepartment.find()
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(parseInt(limit));
    
    // 更新实际学生人数
    for (const dept of departments) {
      const count = await Student.countDocuments({ marketDepartment: dept.name });
      if (count !== dept.studentCount) {
        dept.studentCount = count;
        await dept.save();
      }
    }
    
    const total = await MarketDepartment.countDocuments();
    ok(res, departments.map(mapMarketDepartmentToClient), {
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total,
        totalPages: Math.ceil(total / parseInt(limit))
      }
    });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.getMarketDepartmentById = async (req, res) => {
  try {
    const m = await MarketDepartment.findById(req.params.id);
    if (!m) return fail(res, 404, '未找到该市场部');
    
    // 更新实际学生人数
    const count = await Student.countDocuments({ marketDepartment: m.name });
    if (count !== m.studentCount) {
      m.studentCount = count;
      await m.save();
    }
    
    ok(res, mapMarketDepartmentToClient(m));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.createMarketDepartment = async (req, res) => {
  try {
    const payload = mapClientToMarketDepartment(req.body || {});
    if (!payload.name) {
      return fail(res, 400, '缺少必要字段: name');
    }
    
    const exist = await MarketDepartment.findOne({ name: payload.name });
    if (exist) return fail(res, 400, '市场部名称已存在');
    
    // 计算实际学生人数
    const count = await Student.countDocuments({ marketDepartment: payload.name });
    payload.studentCount = count;
    
    const created = await MarketDepartment.create(payload);
    ok(res, mapMarketDepartmentToClient(created));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.updateMarketDepartment = async (req, res) => {
  try {
    const payload = mapClientToMarketDepartment(req.body || {});
    payload.updatedAt = new Date();
    
    // 如果名称改变，需要更新学生记录
    const oldDept = await MarketDepartment.findById(req.params.id);
    if (oldDept && payload.name !== oldDept.name) {
      await Student.updateMany(
        { marketDepartment: oldDept.name },
        { marketDepartment: payload.name }
      );
    }
    
    // 更新实际学生人数
    const count = await Student.countDocuments({ marketDepartment: payload.name || oldDept.name });
    payload.studentCount = count;
    
    const updated = await MarketDepartment.findByIdAndUpdate(req.params.id, payload, { new: true });
    if (!updated) return fail(res, 404, '未找到该市场部');
    ok(res, mapMarketDepartmentToClient(updated));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.deleteMarketDepartment = async (req, res) => {
  try {
    const deleted = await MarketDepartment.findByIdAndDelete(req.params.id);
    if (!deleted) return fail(res, 404, '未找到该市场部');
    
    // 清除学生的市场部信息
    await Student.updateMany(
      { marketDepartment: deleted.name },
      { $unset: { marketDepartment: 1 } }
    );
    
    ok(res, { id: req.params.id });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

// 更新毕业生现状
exports.updateGraduateStatus = async (req, res) => {
  try {
    const { year, totalGraduates, employed, unemployed, furtherEducation } = req.body;
    if (!year) return fail(res, 400, '缺少必要字段: year');
    
    const dept = await MarketDepartment.findById(req.params.id);
    if (!dept) return fail(res, 404, '未找到该市场部');
    
    const existingIndex = dept.graduateStatus.findIndex(gs => gs.year === year);
    const statusData = {
      year,
      totalGraduates: totalGraduates || 0,
      employed: employed || 0,
      unemployed: unemployed || 0,
      furtherEducation: furtherEducation || 0
    };
    
    if (existingIndex >= 0) {
      dept.graduateStatus[existingIndex] = statusData;
    } else {
      dept.graduateStatus.push(statusData);
    }
    
    dept.updatedAt = new Date();
    await dept.save();
    
    ok(res, mapMarketDepartmentToClient(dept));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

